$(function () {
    event();
    search();
    $('select').selectpicker();
});

var timer;
function refresh(status) {
    if(status && !timer){
        timer = setInterval(function () {
            search();
        },5000)
    }else {
        clearInterval(timer);
        timer = 0;
    }
}
function event() {
    //点击选中并赋值
    $(".input-search-group").on("click", ".dropdown-menu .dropdown-item", function (event) {
        var text = $(this).text();
        $(this).parent(".dropdown-menu").siblings(".dropdown-toggle").text(text);
        var val = $(this).find("[name='item']").val();
        $(this).parent(".dropdown-menu").siblings("input:hidden").val(val);
    });

    $(".input-search-group").on("keydown", "#searchInput", function (event) {
        if (event.keyCode == 13) {
            $("#pageNumber").val("");
            search();
        }
    });
    $(".input-search-group").on("click", "#search", function () {
        $("#pageNumber").val("");
        search();
    });

    $('#timerSwitch').bootstrapSwitch({
        state: false,//开关状态
        size: null,//尺寸 mini small large
        animate: true,//开启动画效果
        disabled: false,//禁用
        readonly: false,
        indeterminate: false,
        inverse: false,//方向反转
        radioAllOff: false,
        onColor: 'success',//开启颜色 primary、info，primary，warning，dark，default ，secondary
        offColor: 'secondary',//关闭颜色 primary、info，primary，warning，dark，default， secondary
        onText: 'ON',//开启时展示的文本
        offText: 'OFF',//关闭时展示的文本
        labelText: '&nbsp',//空白区域的文本
        handleWidth: 'auto',
        labelWidth: 'auto',
        baseClass: 'bootstrap-switch',
        wrapperClass: 'wrapper',
        onInit: function onInit() { },
        onSwitchChange: function onSwitchChange(event,state) {
            $(".bootstrap-switch-label").toggleClass("active");
            refresh(state);
        }
    });
    //查询批量启停
    $(".operate-group").on("click", ".searchStartStop", function (event) {
        var value =  $(this).find("[name='item']").val();
        var query = getQueryForm();
        query.status = value;
        switchStatus({query: query});
        return false;
    });

    //全选、反选、取消全选
    $(".operate-group").on("click", ".checkCurrentPage", function (event) {
        var elements =  $(".cards").find("[name='device']");
        var value =  $(this).find("[name='item']").val();
        if(value == 1){//全选
            $.makeArray(elements).forEach(function (item) {$(item).prop("checked",true)});
        }else if(value == 2){//反选
            $.makeArray(elements).forEach(function (item) {var _this = $(item);_this.prop("checked",!_this.prop('checked'));});
        }else if(value == 3){//取消全选
            $.makeArray(elements).forEach(function (item) {$(item).prop("checked",false)});
        }
    });

    //选中批量启停
    $(".operate-group").on("click", ".checkStartStop", function (event) {
        var devices =  $(".cards").find("[name='device']:checked").map(function (item) { return  JSON.parse($(this).val()); });
        var value =  $(this).find("[name='item']").val();
        var query = getQueryForm();
        query.status = value;
        switchStatus({query: query, devices:$.makeArray(devices)});
        return false;
    });

    //单个启停
    $(".cards").on("click", ".singleStartStop:not(.disabled)", function (event) {
        var deviceVal = $(event.target).parents(".card-body").find("input[name='device']").val();
        var device = JSON.parse(deviceVal);
        var query = getQueryForm();
        var value =  $(this).find("[name='item']").val();
        query.status = value;
        switchStatus({query: query, devices: [device]});
        return false;
    });

    //checkbox 点击 实现选中和反选
    $(".cards").on("click", ".box", function (event) {
        var _this = $(this).find("[name='device']");
        _this.prop("checked",!_this.prop('checked'));
        return false;
    });


    //详情
    $(".cards").on("click", ".details", function (event) {
        var deviceVal = $(event.target).parents(".card-body").find("input[name='device']").val();
        $("#deviceTemp").val(deviceVal);
        var opt = {
            title : "详情",
            width: '900px',
            autoHeight: true,
            url:"/pages/tnt/device/details.html",
        };
        BootstrapDialog.show(opt);
        return false;
    });

    //发送消息
    $(".cards").on("click", ".push", function (event) {
        var deviceVal = $(event.target).parents(".card-body").find("input[name='device']").val();
        $("#deviceTemp").val(deviceVal);
        var opt = {
            title : "推送消息",
            width: '900px',
            autoHeight: true,
            url:"/pages/tnt/device/push.html",
            onShown : function(){
                pushMessageViewLoad();
            },
            buttons: [
                {
                    id: 'push-msg-btn-secondary',
                    label: '取消',
                    cssClass: 'btn-secondary',
                    action: function(dialog) {
                        BootstrapDialog.confirm("确认要取消发送消息吗？",function(flag){
                            if(flag){dialog.close();}
                        });
                    },
                },
                {
                    id: 'push-msg-btn-ok',
                    label: '发送',
                    cssClass: 'btn-dark',
                    action: function(dialog) {
                        push(dialog);
                    },
                }
            ],
        };
        BootstrapDialog.show(opt);
        return false;
    });
}


function  push (dialog){
    var deviceVal =  $("#deviceTemp").val();
    var message = {
        topic:$("#pushMsgForm #topic").val(),
        message:$("#pushMsgForm #message").val(),
        protocol:$("#pushMsgForm #protocol").val(),
    };
    var param = $.extend({},JSON.parse(deviceVal),message);
    $.ajax({
        type: "post",
        dataType: "json",
        contentType : "application/json",
        data: JSON.stringify(param),
        url: '/device/push',
        success: function (response) {
            if (!response || !response.status){
                if(response.detailMsg){
                    BootstrapDialog.error(response.msg ? response.msg : '失败');
                }else{
                    BootstrapDialog.warning(response.msg ? response.msg : '失败');
                }
                return;
            }
            BootstrapDialog.success(response.msg ? response.msg : '成功');
            dialog.close();
        }
    });
}



function search () {
    var pageNumber =  $("#pageNumber").val();
    pageNumber = pageNumber > 1 ? pageNumber : 1;
    var param = getQueryForm();
    param.ts = new Date().getTime();
    param.pageNumber = pageNumber ? pageNumber : 1;
    param.pageSize = 20;
    //在线数量
    $.ajax({
        type: "post",
        dataType: "json",
        url: '/device/global',
        data: param,
        success: function (response) {
            if (!response || !response.data){
                return;
            }
            var record = response.data;
            $(".refreshDateTime").text(record.currentDateTime);
            $(".activeTotal").text(record.activeAmount);
        }
    });
    //分页设备数据
    $.ajax({
        type: "post",
        dataType: "json",
        url: '/device/page',
        data: param,
        success: function (response) {
            var globalCard = $(".global-card");
            var pageSize = response && response.data && response.data.pageSize ? response.data.pageSize : 30;
            var pageNumber = response && response.data && response.data.pageNumber ? response.data.pageNumber : 1;
            if (!response || !response.data || !response.data.records || !response.data.total){
                $(".cards").html("");
            }else {
                $(".cards").html(cardBuilder(response.data.records));
            }
            var pageTotal = response && response.data && response.data.total ? response.data.total : 0;
            pagination(pageTotal,pageSize,pageNumber);
        }
    });
}

function switchStatus (param) {
    if(!param.query.protocol && param.query.status == 1){
        BootstrapDialog.alert("未选择协议");
        return ;
    }
    $.ajax({
        type: "post",
        dataType: "json",
        contentType : "application/json",
        data: JSON.stringify(param),
        url: '/device/switch',
        success: function (response) {
            if (response && !response.status){
                if(response.msg){
                    alert(response.msg);
                }
            }
        }
    });
}

function getQueryForm() {
    var type = $(".input-search-group #searchOption").val();
    var val = $(".input-search-group #searchInput").val();

    var pid = type == 1 ? val : '';
    var cid = type == 2 ? val : '';

    var protocol = $(".input-search-group #protocol").val();

    return {"pid":pid,"cid":cid,"protocol":protocol};
}



function pagination(total,pageSize, pageNumber) {
    var pn = $("#pageNumber").val();
    if(pn == pageNumber){return; }
    $('#pagination').pagination({
        maxSize: 7,
        totals: total,
        page: pageNumber,
        pageSize: pageSize,
        lastText: '尾页', //&raquo;
        firstText: '首页',
        prevText: '上一页',//&laquo;
        nextText: '下一页',
        rotate: true,
        directionLinks: true,
        boundaryLinks: true,
        theme:'',
        btnSize:'',
        onPageClick: function(pageNumber) {
            var pn =  $("#pageNumber").val();
            if(pn == pageNumber){return ;}
            $("#pageNumber").val(pageNumber);
            search();
        },
    });
}

function cardBuilder(records) {
    var dict = {
        vs : {
            "starting" : {icon:"iconfont icon-tingzhi3",value : "2",text : "<span class='text-success'>启动中</span>"},
            "started" : {icon:"iconfont icon-tingzhi3",value : "2",text : "<span class='text-success'>在线</span>"},
            "stopping" : {icon:"iconfont icon-qidong4",value : "1",text : "<span class='text-secondary'>停止中</span>"},
            "stopped" : {icon:"iconfont icon-qidong4",value : "1",text : "<span class='text-secondary'>离线</span>"} ,
            "unknown" : {icon:"iconfont icon-qidong4",value : "1",text :  "<span class='text-secondary'>未启动</span>"},
        },
        ps : {
            1 : "<span>未激活</span>",
            2 : "<span class='text-secondary'>离线</span>",
            3 : "<span class='text-success'>在线</span>",
        },
        push : { icon:"iconfont icon-fasong"},
        details : { icon:"iconfont icon-xiangqing2"},

    };
    if(!records || records.length < 1){ return ;}
    var template = "";
    for(var i = 0 ; i < records.length ; i++){
        var record = records[i];
        var device = JSON.stringify(record).replace(/\"/g,'\&quot;');
        template+='<div class="card-box">'
            +'<div class="card card-'+record.virtualDeviceStatus+'" style="background-image: url(/img/card/'+i+'.jpg);">'
            +'<div class="card-body">'
            +'<div class="box"><input type="checkbox" name="device" value="'+device+'" class="checkbox"><span class="check-hook">√</span></div>'
            +'<h5 class="card-title">'+record.cid+'</h5>'
            +'<p class="card-text">产品：<span name="pid">'+record.pid+'</span></p>'
            +'<p class="card-text">时间：<span name="onlineTIme">'+record.lastOnlineTime+'</span></p>';

        //状态
        template +='<p class="card-text" >状态：<span name="status">';
        if(record.describe){
            template += "<span class='virtual-status text-danger alert-link' title='"+record.describe+"'>"+virtualDeviceStatus[record.virtualDeviceStatus]+"....</span> | <span class='platform-status'>"+platformDeviceStatus[record.platformDeviceStatus]+"</span>";
        }else {
            template += "<span class='virtual-status' >"+dict.vs[record.virtualDeviceStatus].text+"</span> | <span class='platform-status'>"+dict.ps[record.platformDeviceStatus]+"</span>";
        }
        template +='</span>';
        template +=' </p>';


        //协议
        template +='<p class="card-text" >协议：<span name="status">'+record.protocol+'</span></p>';

        //操作 启动、停止按钮
        template+='<p class="card-text card-operate">'
            +'<span class="card-static-operate">'
            +'<span class="operate-box"><span class="operate  details '+dict.details.icon+'"></span></span>'
            +'</span>'
            +'<span class="card-dynamic-operate">';
        var status = dict.vs[record.virtualDeviceStatus];
        template+= '<span class="operate-box"><span class="operate singleStartStop '+status.icon+'"><input type="hidden" name="item" value="'+status.value+'"></span></span>'
            +'<span class="operate-box "><span class="operate push '+dict.push.icon+'"></span></span>'
            +'</span>'
            +'</p>';

        template+="</div>" +
            "<div  class='background-backdrop'></div>" +
            "</div></div>";
    }
    return template;
}